package com.lxyk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxyk.yygh.common.exception.YyghException;
import com.lxyk.yygh.common.helper.HttpRequestHelper;
import com.lxyk.yygh.common.result.ResultCodeEnum;
import com.lxyk.yygh.enums.OrderStatusEnum;
import com.lxyk.yygh.enums.PaymentStatusEnum;
import com.lxyk.yygh.enums.PaymentTypeEnum;
import com.lxyk.yygh.model.order.OrderInfo;
import com.lxyk.yygh.model.order.PaymentInfo;
import com.lxyk.yygh.order.mapper.PaymentMapper;
import com.lxyk.yygh.order.service.OrderService;
import com.lxyk.yygh.order.service.PaymentService;
import com.lxyk.yygh.user.client.HospFeignClient;
import com.lxyk.yygh.vo.order.SignInfoVo;
import io.swagger.annotations.ApiModelProperty;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//交易记录表
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService  {

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private HospFeignClient hospFeignClient;

    /**
     * 保存交易记录
     * @param order
     * @param paymentType 支付类型（1：微信 2：支付宝）
     */
    @Override
    public void savePaymentInfo(OrderInfo order, Integer paymentType) {
        //根据订单id 和支付类型，查询支付记录表是否存在相同订单
        //存在则不保存
        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //orderId和order编号查询
        lambdaQueryWrapper.eq(PaymentInfo::getOutTradeNo,order.getOutTradeNo());
        lambdaQueryWrapper.eq(PaymentInfo::getOrderId,order.getId());
        Integer count = baseMapper.selectCount(lambdaQueryWrapper);
        if(count>0) return;

        //订单不存在，设置相关参数
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(order.getOutTradeNo());
        paymentInfo.setOrderId(order.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setCreateTime(new Date());
        //金额
        paymentInfo.setTotalAmount(order.getAmount());
        //交易内容
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd")+"|"+order.getHosname()+"|"+order.getDepname()+"|"+order.getTitle();
        paymentInfo.setSubject(subject);
        //支付状态  1 支付中
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        paymentMapper.insert(paymentInfo);
    }

    //更改订单状态
    @Override
    public void paySuccess(String out_trade_no, Map<String, String> resultMap) {
        //1、根据订单编号得到支付记录
        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentInfo::getPaymentType,PaymentTypeEnum.WEIXIN.getStatus());//支付方式
        lambdaQueryWrapper.eq(PaymentInfo::getOutTradeNo,out_trade_no);
        PaymentInfo paymentInfo = baseMapper.selectOne(lambdaQueryWrapper);
        if(paymentInfo==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //2、更新支付记录信息
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        // 微信订单号	transaction_id 随机生成的WxPayUtil
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackContent(resultMap.toString());
        //更新
        baseMapper.updateById(paymentInfo);
        //3、根据订单号得到订单信息
        OrderInfo order = orderService.getById(paymentInfo.getOrderId());
        order.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        //4、更新订单信息
        orderService.updateById(order);


        //5、 调用医院接口，更新订单支付信息
        //signInfoVo 获取医院签名信息
        //@ApiModelProperty(value = "api基础路径")
        //private String apiUrl;
        //@ApiModelProperty(value = "签名秘钥")
        //private String signKey;
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(order.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",order.getHoscode());
        reqMap.put("hosRecordId",order.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        //发送请求
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updatePayStatus");
        System.out.println("paySucess"+result);
        if(result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }

    }

    /**
     * 获取支付记录
     * @param orderId
     * @param paymentType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentInfo::getOrderId,orderId);
        lambdaQueryWrapper.eq(PaymentInfo::getPaymentType,paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(lambdaQueryWrapper);
        if(paymentInfo==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        return paymentInfo;
    }
}
